﻿using System;
using System.Windows.Forms;
using System.Drawing;
using System.Data;
using System.Data.Common;
using System.Globalization;
using System.Xml;
using System.Configuration;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using DevExpress.XtraTreeList;
using DevExpress.XtraEditors.Controls;
using DevExpress.LookAndFeel;
using THSLib;
using THSERP.BusinessEntities;
using System.Net;
using System.Net.NetworkInformation;
using DevExpress.XtraGrid.Localization;


namespace THSERP.BaseProvider
{
    /// <summary>
    /// THSApp is the main class which manage all module,screens of THS System
    /// </summary>
    public partial class THSApp
    {
        #region "Static variables for THS Application"
        public static int NumOfOpenedModules = 5;
       public static String CurrentModule = String.Empty;
       public static BaseModuleERP CurrentActiveModule = null;
        public static GUIMain MainScreen;
        public static System.Windows.Forms.Form ActiveScreen;
        public static String CurrentLang;
        public static String CurrentUser;
        private static HRShiftsInfo _workingShift;
        private static DateTime _workingDate;
        private static int _workingPeriod;
        private static int _workingYear;
        public static bool IsSynchronizeDatabase = false;
        public static Hashlist OpenModules = new Hashlist();
        public static Assembly THSERPAssembly;


        private static int _currentUserGroupID;
        private static ADUsersInfo _currentUsersInfo;
        private static ADUserGroupsInfo _currentUserGroupsInfo;
        private static CSCompanysInfo _currentCompanyInfo;
        public static ImageList ToolbarImageList = new ImageList();
        public static ImageList SectionImageList = new ImageList();

        private static SortedList _lookupTables;
        private static SortedList _lookupTableUpdatedDate;

        private static SortedList _fieldFormatGroups;
        private static int _priceDecimal = 2;
        private static int _countLogonFail = 0;
        //Add ,hieu nguyen get static PC name, IPAddress ,04/02/2009
        private static String _pcName;
        private static String _ipAddress;
        //hieu nguyen,Add ,get startup path
        public static String StatUpPath = Application.StartupPath + @"\Img";
        #endregion

        #region Properties


        public static int CountLogonFail
        {
            get
            {
                return _countLogonFail;
            }
            set
            {
                _countLogonFail = value;
            }
        }



        public static ADUsersInfo CurrentUsersInfo
        {
            get
            {
                return _currentUsersInfo;
            }
            set
            {
                _currentUsersInfo = value;
            }
        }

        public static ADUserGroupsInfo CurrentUserGroupInfo
        {
            get
            {
                return _currentUserGroupsInfo;
            }
        }

        public static CSCompanysInfo CurrentCompanyInfo
        {
            get
            {
                return _currentCompanyInfo;
            }
            set
            {
                _currentCompanyInfo = value;
            }
        }

        public static DateTime WorkingDate
        {
            get
            {
                return _workingDate;
            }
            set
            {
                _workingDate = value;
            }
        }

        public static int WorkingPeriod
        {
            get
            {
                return _workingPeriod;
            }
            set
            {
                _workingPeriod = value;
            }
        }

        public static int WorkingYear
        {
            get
            {
                return _workingYear;
            }

            set
            {
                _workingYear = value;
            }
        }
        public static HRShiftsInfo CurrentWorkingShift
        {
            get { return _workingShift; }
            set { _workingShift = value; }
        }
        public static SortedList LookupTables
        {
            get
            {
                return _lookupTables;
            }
            set
            {
                _lookupTables = value;
            }
        }

        public static SortedList LookupTablesUpdatedDate
        {
            get
            {
                return _lookupTableUpdatedDate;
            }
            set
            {
                _lookupTableUpdatedDate = value;
            }
        }

        public static SortedList FieldFormatGroups
        {
            get
            {
                return _fieldFormatGroups;
            }
            set
            {
                _fieldFormatGroups = value;
            }
        }

        public static int PriceDecimal
        {
            get
            {
                return _priceDecimal;
            }

            set
            {
                _priceDecimal = value;
            }
        }
        //Add ,hieu nguyen get static PC name, IPAddress ,04/02/2009
        public static String PCName
        {
            get { return _pcName; }
            set { _pcName = value; }
        }
        public static String IPAddress
        {
            get { return _ipAddress; }
            set { _ipAddress = value; }
        }

        #endregion

        #region Constant
        public const String cstTopResultsSearchControl = "fld_txtTopResults";
        public const int cstTopResults = 10000;
        #endregion

        #region "public functions"
        /// <summary>
        /// Init Main Form Title
        /// </summary>
        public static void InitMainFormTitle()
        {


            RegistryWorker regWoker = new RegistryWorker();
            regWoker.SubKey = "SOFTWARE\\ATS";
            String strCompanyName = regWoker.Read("CompanyName");
            //String strCompanyName = THSApp.CurrentCompanyInfo.CSCompanyDesc;

            MainScreen.Text = strCompanyName;
            MainScreen.Text += " - " + THSApp.CurrentWorkingShift.HRShiftName;
            MainScreen.Text += " - " + DateTime.Now.ToShortDateString();
            MainScreen.Text += " - " + CurrentUser;
            MainScreen.Text += "/" + new ADUserGroupsController().GetObjectNameByID(new ADUsersController().GetUserGroupOfUser(CurrentUser));


        }

        //public static void SwitchConnection(String strBranchName)
        //{
        //    BRBranchsController branchController = new BRBranchsController();
        //    BRBranchsInfo objCurrentBranchsInfo = (BRBranchsInfo)branchController.GetObjectByName(strBranchName);



        //    if (objCurrentBranchsInfo != null)
        //    {
        //        String strDatabase = objCurrentBranchsInfo.BRDatabase;
        //        String strServer = objCurrentBranchsInfo.BRServer;
        //        String strUser = objCurrentBranchsInfo.BRUser;
        //        string strPassword = objCurrentBranchsInfo.BRPassword;

        //        EnCrypto cryp = new EnCrypto();
        //        strPassword = cryp.Decrypt(strPassword);

        //        String strBranchConnectionString = string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3}", strServer, strDatabase, strUser, strPassword);
        //        SqlDbHelper.SwitchConnection(strBranchConnectionString);
        //    }

        //}




        //created by hieu nguyen
        //get foreign key value
        public static String ForeignKeyValue(String strTableName, String strColumName, int iValue)
        {
            String strValueName = string.Empty;
            try
            {


                String strTablePrimary = THSDbUtil.GetPrimaryTableWhichForeignColumnReferenceTo(strTableName, strColumName);
                if (!String.IsNullOrEmpty(strTablePrimary))
                {
                    BaseBusinessController objController = BusinessControllerFactory.GetBusinessController(strTablePrimary + "Controller");
                    if (objController != null)
                        strValueName = objController.GetObjectNoByID(iValue);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("here fail +" + ex.Message);
            }
            return strValueName;
        }
        /// <summary>
        /// Descriptions: Get IP address and Computer name
        /// </summary>
        /// <returns> Get List IP address and computer name</returns>
        public static void GetLocalMachineInfo()
        {
            //To Get the local IP address
            PCName = Dns.GetHostName();
            IPHostEntry objIPHostEntry = Dns.GetHostEntry(PCName);
            //Dns.GethostB
            IPAddress[] objIPAddressList = objIPHostEntry.AddressList;
            foreach (IPAddress ip in objIPAddressList)
            {
                IPAddress = ip.ToString();
            }
        }
        //Add ,hieu nguyen get static PC name, IPAddress ,04/02/2009
        //public static void GetPCNameAndIPAddress()
        //{
        //    List<LocalMachineInfo> lstLocalMachine = THSUtil.GetLocalMachineInfo();
        //    if (lstLocalMachine.Count > 0)
        //    {
        //        foreach (LocalMachineInfo localMachine in lstLocalMachine)
        //        {
        //            PCName = localMachine.PCName;
        //            IPAddress = localMachine.IPAddress;
        //        }
        //    }
        //}

        public static void InvalidateLookupTable ( String strLookupTable )
        {

            THSApp.InitDataToLookupTable( strLookupTable );
            if ( THSApp.LookupTables[strLookupTable]==null )
                return;

            DataTable lookupTable=( (DataSet)THSApp.LookupTables[strLookupTable] ).Tables[0];
            BaseBusinessController objLookupTableController=BusinessControllerFactory.GetBusinessController( strLookupTable+"Controller" );
            if ( THSDbUtil.ColumnIsExist( strLookupTable , "AAUpdatedDate" ) )
            {
                DateTime dtLastCreatedDate=THSDbUtil.GetLastCreatedDateOfTable( strLookupTable );
                DateTime dtLastUpdatedDate=THSDbUtil.GetLastUpdatedDateOfTable( strLookupTable );

                DateTime dateLastUpdateOfLookupEdit=(DateTime)THSApp.LookupTablesUpdatedDate[strLookupTable];
                if ( dtLastUpdatedDate.CompareTo( dateLastUpdateOfLookupEdit )>0 )
                {

                    DataSet dsObjectUpdated=objLookupTableController.GetObjectsByAAUpdatedDate( strLookupTable , dateLastUpdateOfLookupEdit );
                    if ( dsObjectUpdated.Tables.Count>0 )
                    {

                        String strPrimaryColumnName=THSDbUtil.GetTablePrimaryColumn( strLookupTable );
                        foreach ( DataRow row in dsObjectUpdated.Tables[0].Rows )
                        {

                            BusinessObject objBusinessObject=(BusinessObject)objLookupTableController.GetObjectFromDataRow( row );
                            int iObjectID=Convert.ToInt32( THSDbUtil.GetPropertyValue( objBusinessObject , strPrimaryColumnName ) );

                            String strExpression=String.Format( "{0}={1}" , strPrimaryColumnName , iObjectID );
                            DataRow[] row1=lookupTable.Select( strExpression );
                            if ( row1.Length==0 )
                            {
                                lookupTable.ImportRow( row );
                            }
                            else
                            {
                                int index=lookupTable.Rows.IndexOf( row1[0] );
                                String AAStatus=THSDbUtil.GetPropertyValue( objBusinessObject , "AAStatus" ).ToString();
                                if ( AAStatus.Equals( BusinessObject.DeletedAAStatus ) )
                                {
                                    lookupTable.Rows.RemoveAt( index );
                                }
                                else
                                {
                                    lookupTable.Rows.RemoveAt( index );
                                    lookupTable.ImportRow( row );
                                }
                            }
                        }
                    }
                    // Update Last Updated Date of Lookup Table
                    THSApp.LookupTablesUpdatedDate[strLookupTable]=DateTime.Now;
                }
            }
        }
        public static void InitDataToLookupTable(string strLookupTable)
        {

            if (THSApp.LookupTables[strLookupTable] == null)
            {
                BaseBusinessController objBusinessController = BusinessControllerFactory.GetBusinessController(strLookupTable + "Controller");
                if (objBusinessController != null)
                {
                    DataSet ds = objBusinessController.GetAllObjects();
                    THSApp.LookupTables.Add(strLookupTable, ds);
                    THSApp.LookupTablesUpdatedDate.Add(strLookupTable, DateTime.Now);
                }
            }

        }

        public static void InitLookupTables()
        {
            _lookupTables = new SortedList();
            _lookupTableUpdatedDate = new SortedList( );
            _lookupTables.Clear();
            _lookupTableUpdatedDate.Clear();

            
            //GELookupTablesController objGELookupTablesController = new GELookupTablesController();
            //DataSet dsLookupTables = objGELookupTablesController.GetAllObjects();
            //if (dsLookupTables.Tables.Count > 0)
            //{
            //    foreach (DataRow rowLookupTable in dsLookupTables.Tables[0].Rows)
            //    {
            //        GELookupTablesInfo objGELookupTablesInfo = (GELookupTablesInfo)objGELookupTablesController.GetObjectFromDataRow(rowLookupTable);
            //        if (objGELookupTablesInfo != null)
            //        {
            //            if (THSDbUtil.IsExistTable(objGELookupTablesInfo.GELookupTableName))
            //            {
            //                _lookupTableUpdatedDate.Add(objGELookupTablesInfo.GELookupTableName, DateTime.Now);
            //                BaseBusinessController objBusinessController = BusinessControllerFactory.GetBusinessController(objGELookupTablesInfo.GELookupTableName + "Controller");
            //                if (objBusinessController != null)
            //                {
            //                    DataSet ds = objBusinessController.GetAllObjects();
            //                    _lookupTables.Add(objGELookupTablesInfo.GELookupTableName, ds);
            //                }
            //            }
            //        }
            //    }
            //}
        }

        //Thanh Trung adds, 17/10/2008
        public static void InitFieldFormatGroups()
        {
            FieldFormatGroups = new SortedList();
            STFieldFormatGroupsController objFieldFormatGroupsController = new STFieldFormatGroupsController();
            DataSet ds = objFieldFormatGroupsController.GetAllObjects();
            if (ds.Tables.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    STFieldFormatGroupsInfo objFieldFormatGroupsInfo = (STFieldFormatGroupsInfo)objFieldFormatGroupsController.GetObjectFromDataRow(row);
                    if (objFieldFormatGroupsInfo != null)
                    {
                        FieldFormatGroups.Add(objFieldFormatGroupsInfo.STFieldFormatGroupID, objFieldFormatGroupsInfo);
                    }
                }
            }
        }

        public static void DisableActionToolbarOfOpenModules(String strCurrentModuleName)
        {
            foreach (String strModuleName in OpenModules.Keys)
            {
                if (!strModuleName.Equals(strCurrentModuleName))
                {
                    BaseModuleERP module = (BaseModuleERP)OpenModules[strModuleName];
                    if (module.ParentScreen.ToolbarManager.Bars[BaseToolbar.ToolbarAction] != null)
                        module.ParentScreen.ToolbarManager.Bars[BaseToolbar.ToolbarAction].Visible = false;
                }
            }
        }

        public static void EnableActionToolbarOfOpenModules(String strCurrentModuleName)
        {
            foreach (String strModuleName in OpenModules.Keys)
            {
                if (!strModuleName.Equals(strCurrentModuleName))
                {
                    BaseModuleERP module = (BaseModuleERP)OpenModules[strModuleName];
                    if (module.ParentScreen.ToolbarManager.Bars[BaseToolbar.ToolbarAction] != null)
                        module.ParentScreen.ToolbarManager.Bars[BaseToolbar.ToolbarAction].Visible = true;
                }
            }
        }

        public static bool IsExistOpenModulesInAction()
        {
            foreach (String strModuleName in OpenModules.Keys)
            {
                BaseModuleERP module = (BaseModuleERP)OpenModules[strModuleName];
                if (!module.Toolbar.IsNullOrNoneAction())
                    return true;
            }
            return false;
        }


        #region "Functions to Section Manager for Main Form"

        public void InitSectionManagerByCurrentUser(String strUserName)
        {
            ADUsersController objUserController = new ADUsersController();
            int iUserGroupID = objUserController.GetUserGroupOfUser(strUserName);
            ADUserGroupSectionsController objUserGroupSectionController = new ADUserGroupSectionsController();
            DataSet dsUserGroupSections = objUserGroupSectionController.GetUserGroupSectionByUserGroupID(iUserGroupID);
            if (dsUserGroupSections.Tables.Count > 0)
            {
                foreach (DataRow row in dsUserGroupSections.Tables[0].Rows)
                {
                    ADUserGroupSectionsInfo objADUserGroupSectionsInfo = (ADUserGroupSectionsInfo)objUserGroupSectionController.GetObjectFromDataRow(row);
                    DevExpress.XtraNavBar.NavBarGroup fld_navbarGroupApp = new DevExpress.XtraNavBar.NavBarGroup();
                    fld_navbarGroupApp.Appearance.Font = new System.Drawing.Font("Tahoma", 10.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                    fld_navbarGroupApp.Appearance.Options.UseFont = true;
                    fld_navbarGroupApp.Caption = objADUserGroupSectionsInfo.ADUserGroupSectionName;
                    fld_navbarGroupApp.Expanded = true;
                    fld_navbarGroupApp.Name = "fld_navBarGroup" + objADUserGroupSectionsInfo.ADUserGroupSectionID;
                    /*Add Item links in here*/
                    AddModuleToGroupSection(fld_navbarGroupApp, objADUserGroupSectionsInfo.ADUserGroupSectionID);
                    /*End add item links*/


                    THSApp.MainScreen.SectionManager.Groups.Add(fld_navbarGroupApp);
                    THSApp.MainScreen.SectionManager.ActiveGroup = THSApp.MainScreen.SectionManager.Groups[0];
                }
            }
            dsUserGroupSections.Dispose();
        }

        public void AddModuleToGroupSection(DevExpress.XtraNavBar.NavBarGroup fld_navBarGroupApp, int iUserGroupSectionID)
        {
            STModuleToUserGroupSectionsController objModuleToUserGroupSectionController = new STModuleToUserGroupSectionsController();
            DataSet dsModules = objModuleToUserGroupSectionController.GetAllModuleToUserGroupSectionByUserGroupSectionID(iUserGroupSectionID);
            if (dsModules.Tables.Count > 0)
            {
                foreach (DataRow row in dsModules.Tables[0].Rows)
                {
                    STModuleToUserGroupSectionsInfo objSTModuleToUserGroupSectionsInfo = (STModuleToUserGroupSectionsInfo)objModuleToUserGroupSectionController.GetObjectFromDataRow(row);

                    STModulesController objModuleController = new STModulesController();
                    STModulesInfo objModuleInfo = new STModulesInfo();
                    objModuleInfo = (STModulesInfo)objModuleController.GetObjectByID(objSTModuleToUserGroupSectionsInfo.STModuleID);
                    DevExpress.XtraNavBar.NavBarItem fld_navBarItemModule = new DevExpress.XtraNavBar.NavBarItem();
                    fld_navBarItemModule.Caption = new STModuleDescriptionsController().GetDescriptionByModuleNameAndLanguageName(objModuleInfo.STModuleName, THSApp.CurrentLang);
                    fld_navBarItemModule.Name = "fld_navBar" + objModuleInfo.STModuleName;
                    fld_navBarItemModule.SmallImageIndex = THSApp.SectionImageList.Images.IndexOfKey(objModuleInfo.STModuleName);
                    fld_navBarItemModule.Tag = objModuleInfo.STModuleName;
                    fld_navBarItemModule.LinkClicked += new DevExpress.XtraNavBar.NavBarLinkEventHandler(ModuleItem_LinkClicked);

                    THSApp.MainScreen.SectionManager.Items.Add(fld_navBarItemModule);
                    fld_navBarGroupApp.ItemLinks.Add(new DevExpress.XtraNavBar.NavBarItemLink(fld_navBarItemModule));
                }
            }
            dsModules.Dispose();
        }

        private static void ModuleItem_LinkClicked(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            if (e.Link.Item.Tag.ToString().StartsWith("THS_") == true)
            {
                String ProgName = "C:\\THS\\exe\\" + e.Link.Item.Tag.ToString().Substring(6) + ".exe";

                if (System.IO.File.Exists(ProgName) == true)
                    System.Diagnostics.Process.Start(ProgName, "1 2 BB_##TEST");
                else
                    MessageBox.Show("Programm : " + ProgName + " nicht gefunden");

                return;
            }
            ShowModule(e.Link.Item.Tag.ToString());
        }

        public static void SetActiveGroupByModule(String strModuleName)
        {
            DevExpress.XtraNavBar.NavBarItem moduleItem = THSApp.MainScreen.SectionManager.Items["fld_navBar" + strModuleName];
            DevExpress.XtraNavBar.NavBarItemLink moduleItemLink = moduleItem.Links[0];
            THSApp.MainScreen.SectionManager.ActiveGroup = moduleItemLink.Group;
            THSApp.MainScreen.SectionManager.SelectedLink = moduleItemLink;
        }

        #endregion

        #region --Treelist--
        private static void InitRootTreeListManagerByCurrentUser(String strUserName)
        {
            THSApp.MainScreen.TreeListSectionManager.StateImageList = THSApp.SectionImageList;

            ADUsersController objUserController = new ADUsersController();
            int iUserGroupID = objUserController.GetUserGroupOfUser(strUserName);
            ADUserGroupSectionsController objUserGroupSectionController = new ADUserGroupSectionsController();
            DataSet dsUserGroupSections = objUserGroupSectionController.GetUserGroupSectionByUserGroupID(iUserGroupID);
            if (dsUserGroupSections.Tables.Count > 0)
            {
                foreach (DataRow row in dsUserGroupSections.Tables[0].Rows)
                {
                    ADUserGroupSectionsInfo objADUserGroupSectionsInfo = (ADUserGroupSectionsInfo)objUserGroupSectionController.GetObjectFromDataRow(row);

                    //THSApp.MainScreen.TreeListSectionManager.Columns.AddField( "Modules" );
                    //THSApp.MainScreen.TreeListSectionManager.PopulateColumns();
                    //THSApp.MainScreen.TreeListSectionManager.BestFitColumns();

                    //  THSApp.MainScreen.TreeListSectionManager.BeginUnboundLoad();
                    DevExpress.XtraTreeList.Nodes.TreeListNode treelstNode = THSApp.MainScreen.TreeListSectionManager.AppendNode(new object[] { objADUserGroupSectionsInfo.ADUserGroupSectionName }, null);
                    treelstNode.HasChildren = true;

                    AddModuleToChildNode(treelstNode, objADUserGroupSectionsInfo.ADUserGroupSectionID);
                    //    THSApp.MainScreen.TreeListSectionManager.EndUnboundLoad();
                }
            }
            dsUserGroupSections.Dispose();

            THSApp.MainScreen.TreeListSectionManager.NodeCellStyle += new DevExpress.XtraTreeList.GetCustomNodeCellStyleEventHandler(TreeListSectionManager_NodeCellStyle);
            THSApp.MainScreen.TreeListSectionManager.MouseClick += new MouseEventHandler(TreeListSectionManager_MouseClick);
            THSApp.MainScreen.TreeListSectionManager.MouseMove += new MouseEventHandler(TreeListSectionManager_MouseMove);
            THSApp.MainScreen.TreeListSectionManager.MouseLeave += new EventHandler(TreeListSectionManager_MouseLeave);

            THSApp.MainScreen.TreeListSectionManager.ExpandAll();
        }

        private static void AddModuleToChildNode(DevExpress.XtraTreeList.Nodes.TreeListNode treelstParent, int iUserGroupSectionID)
        {
            STModuleToUserGroupSectionsController objModuleToUserGroupSectionController = new STModuleToUserGroupSectionsController();
            DataSet dsModules = objModuleToUserGroupSectionController.GetAllModuleToUserGroupSectionByUserGroupSectionID(iUserGroupSectionID);
            if (dsModules.Tables.Count > 0)
            {
                foreach (DataRow row in dsModules.Tables[0].Rows)
                {
                    STModuleToUserGroupSectionsInfo objSTModuleToUserGroupSectionsInfo = (STModuleToUserGroupSectionsInfo)objModuleToUserGroupSectionController.GetObjectFromDataRow(row);

                    STModulesController objModuleController = new STModulesController();
                    STModulesInfo objModuleInfo = new STModulesInfo();
                    objModuleInfo = (STModulesInfo)objModuleController.GetObjectByID(objSTModuleToUserGroupSectionsInfo.STModuleID);

                    string strCaption = new STModuleDescriptionsController().GetDescriptionByModuleNameAndLanguageName(objModuleInfo.STModuleName, THSApp.CurrentLang);
                    DevExpress.XtraTreeList.Nodes.TreeListNode treelstNode = THSApp.MainScreen.TreeListSectionManager.AppendNode(new object[] { strCaption }, treelstParent);
                    treelstNode.HasChildren = false;
                    treelstNode.Tag = objModuleInfo.STModuleName;
                    treelstNode.StateImageIndex = THSApp.SectionImageList.Images.IndexOfKey(objModuleInfo.STModuleName);
                }
            }
            dsModules.Dispose();
        }

        public static void SetActiveModuleByModuleName(String strModuleName)
        {
            THSApp.CurrentModule = strModuleName;
            THSApp.MainScreen.TreeListHotTrackID = -1;
            foreach (DevExpress.XtraTreeList.Nodes.TreeListNode treeParentNode in THSApp.MainScreen.TreeListSectionManager.Nodes)
            {
                foreach (DevExpress.XtraTreeList.Nodes.TreeListNode treeItemNode in treeParentNode.Nodes)
                {
                    if (treeItemNode.Tag.Equals(strModuleName))
                    {
                        treeParentNode.ExpandAll();
                        THSApp.MainScreen.TreeListSectionManager.SetFocusedNode(treeItemNode);
                        return;
                    }
                }
            }
            THSApp.MainScreen.TreeListSectionManager.Refresh();
        }

        private static void TreeListSectionManager_NodeCellStyle(object sender, DevExpress.XtraTreeList.GetCustomNodeCellStyleEventArgs e)
        {
            if (e.Node.Tag != null && e.Node.Tag.ToString() == THSApp.CurrentModule)
            {
                e.Appearance.Font = new Font(DevExpress.Utils.AppearanceObject.DefaultFont, FontStyle.Underline);
                e.Appearance.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.Vertical;
                e.Appearance.BackColor = Color.Yellow;
                e.Appearance.BackColor2 = Color.Tomato;
                return;
            }

            if (e.Node.Id == THSApp.MainScreen.TreeListHotTrackID)
            {
                e.Appearance.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal;
                e.Appearance.BackColor = Color.Transparent;
                e.Appearance.BackColor2 = Color.Orange;
                return;
            }

            if (e.Node.HasChildren)
            {
                Font tempfont = new Font("Tahoma", (float)10, FontStyle.Bold);
                e.Appearance.Font = tempfont;
                e.Appearance.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.Vertical;
                e.Appearance.BackColor = Color.Silver;
                e.Appearance.BackColor2 = Color.White;
                return;
            }
            else
            {
                e.Appearance.BackColor = Color.White;
                e.Appearance.BackColor2 = Color.White;
                return;
            }
        }

        private static void TreeListSectionManager_MouseClick(object sender, MouseEventArgs e)
        {
            TreeList treelst = (TreeList)sender;
            TreeListHitInfo treeHitInfo = treelst.CalcHitInfo(e.Location);
            //TreeListSectionManager.Cursor = Cursors.Default;
            if (treeHitInfo.Node != null)
            {
                if (treeHitInfo.Node.Tag != null)
                {
                    String strModuleName = treeHitInfo.Node.Tag.ToString();
                    if (!String.IsNullOrEmpty(strModuleName))
                    {
                        THSApp.SetActiveModuleByModuleName(strModuleName);
                        ShowModule(strModuleName);
                    }
                }
            }
        }

        private static void TreeListSectionManager_MouseMove(object sender, MouseEventArgs e)
        {
            TreeList treelst = (TreeList)sender;
            TreeListHitInfo treeHitInfo = treelst.CalcHitInfo(e.Location);
            //TreeListSectionManager.Cursor = Cursors.Default;
            if (treeHitInfo.Node != null)
            {
                //TreeListSectionManager.Cursor = Cursors.Hand;
                if (treeHitInfo.Node.Tag != null)
                {
                    THSApp.MainScreen.TreeListHotTrackID = treeHitInfo.Node.Id;
                    THSApp.MainScreen.TreeListSectionManager.Refresh();
                }

            }
        }

        private static void TreeListSectionManager_MouseLeave(object sender, EventArgs e)
        {
            THSApp.MainScreen.TreeListHotTrackID = -1;
            THSApp.MainScreen.TreeListSectionManager.Refresh();
        }
        #endregion

        #region Utility Functions
        public static void InitToolbarImageList()
        {
            try
            {
                ToolbarImageList.ImageSize = new Size(16, 16);
                ToolbarImageList.ColorDepth = ColorDepth.Depth32Bit;
                String strToolbarImagePath = Application.StartupPath + "\\img\\Toolbar";
                DirectoryInfo dir = new DirectoryInfo(strToolbarImagePath);
                foreach (FileInfo file in dir.GetFiles())
                {
                    if (file.Extension.ToLower() == ".ico" || file.Extension.ToLower() == ".png" || file.Extension.ToLower() == ".jpg" || file.Extension.ToLower() == ".bmp")
                    {
                        int index = file.Name.IndexOf(".");
                        if (index > 0)
                        {
                            String strKey = file.Name.Substring(0, index);
                            Image img = Image.FromFile(file.FullName);
                            ToolbarImageList.Images.Add(strKey, img);
                        }
                    }
                }
            }
            catch (Exception)
            {

            }
        }

        public static void InitSectionImageList()
        {
            try
            {
                SectionImageList.ImageSize = new Size(12, 12);
                SectionImageList.ColorDepth = ColorDepth.Depth32Bit;
                String strSectionImagePath = Application.StartupPath + "\\img\\Section";
                DirectoryInfo dir = new DirectoryInfo(strSectionImagePath);
                foreach (FileInfo file in dir.GetFiles())
                {
                    if (file.Extension.ToLower() == ".ico" || file.Extension.ToLower() == ".png" || file.Extension.ToLower() == ".jpg" || file.Extension.ToLower() == ".bmp")
                    {
                        int index = file.Name.IndexOf(".");
                        if (index > 0)
                        {
                            String strKey = file.Name.Substring(0, index);
                            Image img = Image.FromFile(file.FullName);
                            SectionImageList.Images.Add(strKey, img);
                        }
                    }
                }
            }
            catch (Exception)
            {

            }
        }

        public static void SetApplicationStyle(String strLookAndFeelStyle, String strLookAndFeelStyleSkin)
        {
            if (strLookAndFeelStyle == "Skin")
            {
                if (!String.IsNullOrEmpty(strLookAndFeelStyleSkin))
                    DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(strLookAndFeelStyleSkin);
                else
                    DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle("Black");
            }
            else
            {
                DevExpress.LookAndFeel.LookAndFeelStyle style = DevExpress.LookAndFeel.LookAndFeelStyle.Office2003;
                try
                {
                    style = (DevExpress.LookAndFeel.LookAndFeelStyle)Enum.Parse(typeof(DevExpress.LookAndFeel.LookAndFeelStyle), strLookAndFeelStyle);
                }
                catch (Exception)
                {
                    
                    style = DevExpress.LookAndFeel.LookAndFeelStyle.Office2003;
                }

                DevExpress.LookAndFeel.UserLookAndFeel.Default.SetStyle(style, false, true);
            }
        }

        public static void SaveUserStyle(String strLookAndFeelStyle, String strLookAndFeelStyleSkin)
        {
            ADUsersInfo objADUsersInfo = (ADUsersInfo)new ADUsersController().GetObjectByName(THSApp.CurrentUser);
            objADUsersInfo.ADUserStyle = strLookAndFeelStyle;
            objADUsersInfo.ADUserStyleSkin = strLookAndFeelStyleSkin;

            new ADUsersController().UpdateObject(objADUsersInfo);
        }

        /// <summary>
        /// Init menu main form
        /// </summary>
        /// 
        public static void InitMenuOfMainForm()
        {
            ADUsersController objUserController = new ADUsersController();
            int iUserGroupID = objUserController.GetUserGroupOfUser(THSApp.CurrentUser);
            ADUserGroupSectionsController objUserGroupSectionController = new ADUserGroupSectionsController();
            DataSet dsUserGroupSections = objUserGroupSectionController.GetUserGroupSectionByUserGroupID(iUserGroupID);
            if (dsUserGroupSections.Tables.Count > 0)
            {
                for (int i = 0; i < dsUserGroupSections.Tables[0].Rows.Count; i++)
                {
                    ADUserGroupSectionsInfo objADUserGroupSectionsInfo = (ADUserGroupSectionsInfo)objUserGroupSectionController.GetObjectFromDataRow(dsUserGroupSections.Tables[0].Rows[i]);
                    DevExpress.XtraBars.BarSubItem item = new DevExpress.XtraBars.BarSubItem();
                    item.Caption = objADUserGroupSectionsInfo.ADUserGroupSectionName;
                    THSApp.MainScreen.MainMenu.InsertItem(THSApp.MainScreen.MainMenu.ItemLinks[2+i], item);
                    item = AddSubMenuToMenuItem(item, objADUserGroupSectionsInfo.ADUserGroupSectionID);
                }
            }
        }
        public static bool ValidUserStatus(String strModuleName)
        {
            try
            {
                int iUserID = new ADUsersController().GetObjectIDByName(CurrentUser);
                GEUserAuditsController objGEUserAuditsController = new GEUserAuditsController();
                GEUserAuditsInfo objGEUserAuditsInfo = (GEUserAuditsInfo)objGEUserAuditsController.GetGEUserAuditsByADUserIDAndModuleName(iUserID, strModuleName);
                if (objGEUserAuditsInfo != null)
                {
                    if (objGEUserAuditsInfo.GEUserAuditPCName.Equals(PCName) && objGEUserAuditsInfo.GEUserAuditIP.Equals(IPAddress))
                        return true;

                }
                else
                    return false;

            }
            catch (Exception ex)
            { }
            return false;
        }
        /// <summary>
        /// Init sub menu to menu item
        /// </summary>
        /// 
        public static DevExpress.XtraBars.BarSubItem AddSubMenuToMenuItem(DevExpress.XtraBars.BarSubItem menuItem, int userGroupSectionID)
        {
            STModuleToUserGroupSectionsController objSTModuleToUserGroupSectionsController = new STModuleToUserGroupSectionsController();
            DataSet dsModuleUserGroupSections = objSTModuleToUserGroupSectionsController.GetAllDataByForeignColumn("STUserGroupSectionID", userGroupSectionID);
            if (dsModuleUserGroupSections != null)
            {
                foreach (DataRow row in dsModuleUserGroupSections.Tables[0].Rows)
                {
                    STModuleToUserGroupSectionsInfo objSTModuleToUserGroupSectionsInfo = (STModuleToUserGroupSectionsInfo)objSTModuleToUserGroupSectionsController.GetObjectFromDataRow(row);
                    if (objSTModuleToUserGroupSectionsInfo != null)
                    {
                        STModulesInfo objSTModulesInfo = (STModulesInfo)new STModulesController().GetObjectByID(objSTModuleToUserGroupSectionsInfo.STModuleID);
                        STModuleDescriptionsController objModuleDescriptionsController = new STModuleDescriptionsController();
                        STModuleDescriptionsInfo objModuleDescriptionsInfo = (STModuleDescriptionsInfo)objModuleDescriptionsController.GetObjectByModuleID(objSTModulesInfo.STModuleID);
                        DevExpress.XtraBars.BarButtonItem subItem = new DevExpress.XtraBars.BarButtonItem();
                        subItem.Caption = objModuleDescriptionsInfo.STModuleDescriptionDescription;
                        subItem.Tag = objSTModulesInfo.STModuleID;
                        subItem.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(subItem_ItemClick);
                        menuItem.AddItem(subItem);
                    }
                }
            }
            return menuItem;
        }
        /// <summary>
        /// Init toolbar of main form
        /// </summary>
        ///

        public static void InitToolbarOfMainForm()
        {
            //hieu.nguyen remove toolbar on mainform
          //  THSApp.MainScreen.Toolbar.ClearLinks();
            STToolbarsController objToolbarsController = new STToolbarsController();
            DataSet ds = objToolbarsController.GetSTToolbarsBySTModuleIDAndSTUserGroupID(0, 0);
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                STToolbarsInfo objToolbarsInfo = (STToolbarsInfo)objToolbarsController.GetObjectFromDataRow(row);
                STModulesInfo objModulesInfo = (STModulesInfo)new STModulesController().GetObjectByName(objToolbarsInfo.STToolbarTag);
                if (objModulesInfo != null)
                {
                    if (THSApp.HasPrivilege(objToolbarsInfo.STToolbarPrivilege, objModulesInfo.STModuleID) && objToolbarsInfo.STToolbarVisible == true)
                    {
                        DevExpress.XtraBars.BarLargeButtonItem toolbarItem = new DevExpress.XtraBars.BarLargeButtonItem();
                        toolbarItem.Caption = objToolbarsInfo.STToolbarCaption;
                        toolbarItem.Name = objToolbarsInfo.STToolbarName;
                        toolbarItem.Tag = objToolbarsInfo.STToolbarID;
                        toolbarItem.LargeImageIndex = THSApp.ToolbarImageList.Images.IndexOfKey(toolbarItem.Caption);
                        toolbarItem.ImageIndex = THSApp.ToolbarImageList.Images.IndexOfKey(toolbarItem.Caption);
                        toolbarItem.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(toolbarItem_ItemClick);
                        //hieu.nguyen remove toolbar on mainform
                       // THSApp.MainScreen.Toolbar.AddItem(toolbarItem);
                    }
                }
            }
        }

        /// <summary>
        /// Show module when click submenu item.
        /// </summary>
        /// 

        private static void subItem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            int moduleID = (int)e.Item.Tag;
            STModulesInfo objModuleInfo = (STModulesInfo)new STModulesController().GetObjectByID(moduleID);
            if (!String.IsNullOrEmpty(objModuleInfo.STModuleName))
            {
                THSApp.SetActiveModuleByModuleName(objModuleInfo.STModuleName);
                ShowModule(objModuleInfo.STModuleName);
            }
        }

        /// <summary>
        /// Solve click event when user click on toolbar button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 

        private static void toolbarItem_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            STToolbarsInfo objToolbarsInfo = (STToolbarsInfo)new STToolbarsController().GetObjectByID((int)e.Item.Tag);
            STToolbarFunctionsController objToolbarFunctionsController = new STToolbarFunctionsController();
            DataSet ds = objToolbarFunctionsController.GetAllDataByForeignColumn("STToolbarID", objToolbarsInfo.STToolbarID);

            THSApp.SetActiveModuleByModuleName(objToolbarsInfo.STToolbarTag);
            ShowModule(objToolbarsInfo.STToolbarTag);

            if (ds.Tables[0].Rows.Count > 0)
            {
                STToolbarFunctionsInfo objToolbarFucntionsInfo = (STToolbarFunctionsInfo)objToolbarFunctionsController.GetObjectFromDataRow(ds.Tables[0].Rows[0]);
                BaseModuleERP currModule = (BaseModuleERP)THSApp.OpenModules[THSApp.CurrentModule];
                if (objToolbarFucntionsInfo != null)
                {
                    MethodInfo methodInfo = currModule.GetMethodInfoByMethodFullNameAndMethodClass(objToolbarFucntionsInfo.STToolbarFunctionName, objToolbarFucntionsInfo.STToolbarFunctionFullName, objToolbarFucntionsInfo.STToolbarFunctionClass);
                    if (methodInfo != null)
                        methodInfo.Invoke(currModule, null);
                }
            }
        }

        /// <summary>
        /// Use for check privilege of main form toolbar.
        /// </summary>
        /// <param name="privilegeName"></param>
        /// <param name="moduleID"></param>
        /// <returns></returns>
        ///

        public static bool HasPrivilege(String privilegeName, int moduleID)
        {
            //Check current user group
            bool rs = false;
            ADUserGroupsInfo objUserGroupsInfo = THSApp.CurrentUserGroupInfo;
            ADUserGroupSectionsController objUserGroupSectionsController = new ADUserGroupSectionsController();
            DataSet ds = objUserGroupSectionsController.GetAllDataByForeignColumn("ADUserGroupID", objUserGroupsInfo.ADUserGroupID);
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                ADUserGroupSectionsInfo objUserGroupSectionsInfo = (ADUserGroupSectionsInfo)objUserGroupSectionsController.GetObjectFromDataRow(row);
                STModuleToUserGroupSectionsController objModuleToUserGroupSectionsController = new STModuleToUserGroupSectionsController();
                DataSet ds1 = objModuleToUserGroupSectionsController.GetAllDataByForeignColumn("STUserGroupSectionID", objUserGroupSectionsInfo.ADUserGroupSectionID);
                foreach (DataRow row1 in ds1.Tables[0].Rows)
                {
                    STModuleToUserGroupSectionsInfo objModuleToUserGroupSectionsInfo = (STModuleToUserGroupSectionsInfo)objModuleToUserGroupSectionsController.GetObjectFromDataRow(row1);
                    if (objModuleToUserGroupSectionsInfo.STModuleID == moduleID)
                    {
                        rs = true;
                        break;
                    }
                }
                if (rs == true)
                    break;
            }
            //Current user group has not obtain module
            if (rs == false)
                return false;

            if (!String.IsNullOrEmpty(privilegeName))
            {
                ADPrivilegesController objPrivilegesController = new ADPrivilegesController();
                ADPrivilegesInfo objPrivilegesInfo = objPrivilegesController.GetPrivilegeByNameAndModuleID(privilegeName, moduleID);
                if (objPrivilegesInfo == null)
                    return true;
                ADPrivilegeUserGroupsController objPrivilegeUserGroupsController = new ADPrivilegeUserGroupsController();
                ADPrivilegeUserGroupsInfo objPrivilegeUserGroupsInfo = objPrivilegeUserGroupsController.GetObjectByPrivilegeIDAndUserGroupID(objPrivilegesInfo.ADPrivilegeID, THSApp.CurrentUserGroupInfo.ADUserGroupID);

                if (objPrivilegeUserGroupsInfo == null || objPrivilegeUserGroupsInfo.ADPrivilegeUserGroupCheck == false)
                    return false;
            }
            return true;
        }

        #endregion

        public static void LogOn()
        {

            guiLogin _guiLogin = new guiLogin();
            _guiLogin.ShowDialog();
            if (_guiLogin.DialogResult== DialogResult.OK)
            {
                //Set application style for current user
                ADUsersController objUsersController = new ADUsersController();
                ADUsersInfo objUsersInfo = (ADUsersInfo)objUsersController.GetObjectByName(THSApp.CurrentUser);
                if (objUsersInfo != null)
                    THSApp.SetApplicationStyle(objUsersInfo.ADUserStyle, objUsersInfo.ADUserStyleSkin);
                //set current user
                THSApp.CurrentUsersInfo = objUsersInfo;
                InitToolbarImageList();
                InitSectionImageList();
                MainScreen.BarManager.LargeImages = ToolbarImageList;


                //MainScreen.SectionManager.SmallImages = SectionImageList;
                //InitSectionManagerByCurrentUser(THSApp.CurrentUser);

                THSApp.InitRootTreeListManagerByCurrentUser(THSApp.CurrentUser);

                ADConfigValueUtility.InitGlobalConfigValueTables();
                //A1CompanyConfigUtility.CompanyConfigInit();
                InitMainFormTitle();

                InitLookupTables();


                InitFieldFormatGroups();

                _currentUserGroupID = new ADUsersController().GetUserGroupOfUser(THSApp.CurrentUser);
                _currentUserGroupsInfo = (ADUserGroupsInfo)new ADUserGroupsController().GetObjectByID(_currentUserGroupID);

                //Get Current Company Info
                CSCompanysController objCSCompanysController = new CSCompanysController();
                _currentCompanyInfo = (CSCompanysInfo)objCSCompanysController.GetFirstObject();
                //Init Report Connection
                //ReportHelper.SetReportConnection();

                //Init status bar items
                THSApp.MainScreen.userItem.Caption = THSApp.CurrentUserGroupInfo.ADUserGroupName + "\\" + THSApp.CurrentUser;
               // THSApp.MainScreen.dateItem.Caption = DateTime.Now.ToShortDateString();
                THSApp.MainScreen.dateItem.Caption = THSApp.WorkingDate.ToShortDateString();
                //Add Menu to main form
                InitMenuOfMainForm();
                InitToolbarOfMainForm();

                //Show home page
                if (CurrentUserGroupInfo.ADUserGroupName.Contains("SALE"))
                    THSApp.ShowModule("POS");
                else if (CurrentUserGroupInfo.ADUserGroupName.Contains("Accounting"))
                    THSApp.ShowModule("TaxDec");
                else
                {
                    STModuleToUserGroupSectionsInfo objModuleToUserGroupSectionsInfo = new STModuleToUserGroupSectionsController().GetModuleToUserGroupSectionByModuleNameAndUserGroupID("CompanyConstant", THSApp.CurrentUserGroupInfo.ADUserGroupID);
                    if (objModuleToUserGroupSectionsInfo != null)
                        THSApp.ShowModule("CompanyConstant");
                }
            }
        }

        /// <summary>
        /// log off
        /// hieu.nguyen
        /// 91/7/2011
        /// </summary>
        /// 
        public static void CloseAllModuleBeforeLogOff()
        {
            //Clear section manager and enable if current section manager is not enable
            THSApp.MainScreen.SectionManager.Groups.Clear();
            THSApp.MainScreen.SectionManager.Enabled = true;
            //Close all open modules,clear all in Open Module list and tool strip .Enable Open module tool strip
            CloseAllOpenModules();
            OpenModules.Clear();
            THSApp.MainScreen.OpenModulesToolStrip.Items.Clear();
            THSApp.MainScreen.OpenModulesToolStrip.Enabled = true;
            THSApp.MainScreen.TreeListSectionManager.ClearNodes();
            for (int i = THSApp.MainScreen.MainMenu.ItemLinks.Count - 1; i > 0; i--)
            {
                DevExpress.XtraBars.BarItemLink item = (DevExpress.XtraBars.BarItemLink)THSApp.MainScreen.MainMenu.ItemLinks[i];
                if (item != null)
                {
                    if (item.Item.Tag == null)
                    {
                        THSApp.MainScreen.MainMenu.ItemLinks.RemoveAt(i);
                    }
                }
            }

            //THSApp.MainScreen.Toolbar.ClearLinks();
            //Set AppInfoBar is Empty
            //THSApp.MainScreen.AppInfoBar.Text = String.Empty;
            //clear current usergroup
            MainScreen.Text = ConfigurationManager.AppSettings["CompanyName"];
            if (THSApp.CurrentUser != null)
            {
                int iADUserID = new ADUsersController().GetObjectIDByName(THSApp.CurrentUser);
                new GEUserAuditsController().DeleteGEUserAuditsByADUserID(iADUserID);
            }
        }
        public static void LogOff()
        {
            if (THSApp.OpenModules.Count > 0 && THSApp.IsExistOpenModulesInAction())
            {
                guiLogOffWarning _guiLogOffWarning = new guiLogOffWarning();
                _guiLogOffWarning.ShowDialog();
                return;
            }
            DialogResult dlgresult = MessageQuestion.ShowMessageLogOffQuestion(THSApp.CurrentUser);
            if (dlgresult == DialogResult.Yes)
            {   //Log on again
                CloseAllModuleBeforeLogOff();
                LogOn();
            }
        }

        /// <summary>
        /// Show Module with module Name
        /// </summary>
        /// <param name="strModuleName">Module Name</param>
        public static void ShowModule(String strModuleName)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                //Show new module                   
                //If module will be show is in Opened Module List, get this module and show
                if (THSApp.IsOpenedModule(strModuleName))
                {
                    ShowOpenedModule(strModuleName);
                }
                //if module is not in Opened Module List, create new instance and show
                else
                {
                    BaseModuleERP module = BaseModuleFactory.GetModule(strModuleName);
                    if (module != null)
                        ShowNewModule(module);
                }

                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                return;
            }
        }

        /// <summary>
        /// Show module have already exist on Opend Modules List
        /// </summary>
        /// <param name="strModuleName"></param>
        private static void ShowOpenedModule(String strModuleName)
        {
            ToolStripButton tsbtnModule = (ToolStripButton)THSApp.MainScreen.OpenModulesToolStrip.Items[strModuleName];
            CheckOpenModuleToolStripButton(tsbtnModule);
            BaseModuleERP module = (BaseModuleERP)THSApp.OpenModules[strModuleName];
            module.ParentScreen.Activate();
        }

        /// <summary>
        /// Show new module
        /// </summary>
        /// <param name="module"></param>
        private static void ShowNewModule(BaseModuleERP module)
        {

            AddOpenModuleToOpenModulesToolStrip(module.Name);
            module.Show();
        }

        /// <summary>
        /// Populate ToolStrip Button for open module
        /// </summary>
        /// <param name="strModuleName">Name of Module will be populated to toolstrip button</param>
        /// <returns></returns>
        private static ToolStripButton PopulateOpenModulesToolStripButton(String strModuleName)
        {
            String strModuleDesc = new STModuleDescriptionsController().GetDescriptionByModuleNameAndLanguageName(strModuleName, THSApp.CurrentLang);
            if (String.IsNullOrEmpty(strModuleDesc))
                strModuleDesc = strModuleName;

            ToolStripButton tsbtnOpenModules = new ToolStripButton(strModuleDesc, THSApp.SectionImageList.Images[strModuleName], OpenModulesToolStrip_Click, strModuleName);
            tsbtnOpenModules.TextImageRelation = TextImageRelation.ImageBeforeText;
            tsbtnOpenModules.CheckOnClick = true;
            return tsbtnOpenModules;
        }



        /// <summary>
        /// Set toolstripbutton of Open Module to checked
        /// </summary>
        /// <param name="tsbtnModule"></param>
        public static void CheckOpenModuleToolStripButton(ToolStripButton tsbtnModule)
        {
            tsbtnModule.Checked = true;
            foreach (ToolStripButton tsbtnOpenedModule in THSApp.MainScreen.OpenModulesToolStrip.Items)
            {
                if (tsbtnOpenedModule.Name != tsbtnModule.Name)
                    tsbtnOpenedModule.Checked = false;
            }
        }


        /// <summary>
        /// Delegate function for event click of Toolstrip Button Open Module
        /// </summary>
        /// <param name="sender">sender object</param>
        /// <param name="e">Event Arugment</param>
        private static void OpenModulesToolStrip_Click(object sender, EventArgs e)
        {
            ToolStripButton tsbtnModule = (ToolStripButton)sender;
            CheckOpenModuleToolStripButton(tsbtnModule);
            ShowModule(tsbtnModule.Name);
            //SetActiveGroupByModule(tsbtnModule.Name);
        }


        /// <summary>
        /// Add open module to Open Modules Tool Strip
        /// </summary>
        /// <param name="strModuleName">Name of module will be added</param>
        /// 
        public static void AddOpenModuleToOpenModulesToolStrip(String strModuleName)
        {
            ToolStripButton tsbtnModule = PopulateOpenModulesToolStripButton(strModuleName);
            THSApp.MainScreen.OpenModulesToolStrip.Items.Add(tsbtnModule);

            tsbtnModule.Visible = true;
            CheckOpenModuleToolStripButton(tsbtnModule);
        }


        /// <summary>
        /// Check the module is opened before or not
        /// </summary>
        /// <param name="strModuleName">Name of module is checked</param>
        /// <returns>true if is opened before, otherwise return false</returns>
        /// 
        public static bool IsOpenedModule(String strModuleName)
        {
            return OpenModules.ContainsKey(strModuleName);
        }

        /// <summary>
        /// Add new or update module into Opened Module list
        /// </summary>
        /// <param name="module">module will be added new or updated</param>
        public static void UpdateOpenedModule(BaseModuleERP module)
        {
            if (!IsOpenedModule(module.Name))
            {
                if (!module.Name.Equals(BaseModuleERP.cstHomeModule))
                    OpenModules.Add(module.Name, module);
            }
            else
                OpenModules[module.Name] = module;
        }

        /// <summary>
        /// Remove module from Opened Module list
        /// </summary>
        /// <param name="module">Module will be removed</param>
        public static void RemoveOpenedModule(BaseModuleERP module)
        {
            if (IsOpenedModule(module.Name))
            {
                ((BaseModuleERP)OpenModules[module.Name]).Close();
                OpenModules.Remove(module.Name);
            }
        }

        /// <summary>
        /// Remove module from Opened module list
        /// </summary>
        /// <param name="strModuleName">Module name will be removed</param>
        public static void RemoveOpenedModule(String strModuleName)
        {
            if (IsOpenedModule(strModuleName))
                OpenModules.Remove(strModuleName);
        }


        public static void CloseAllOpenModules()
        {
            int j = 0;
            for (int i = OpenModules.Count-1;i>=0 ; i--)
            {
                BaseModuleERP module = (BaseModuleERP)OpenModules[i];
                if (module != null)
                {
                    module.Close();
                   // if (i == 0)
                        module.ParentScreen.Close();
                    OpenModules.Remove(module);
                   
                }
            }
            //foreach (DictionaryEntry de in OpenModules)
            //{
            //    i++;
            //    BaseModuleERP module = (BaseModuleERP)de.Value;
            //    module.Close();
            //    //if (i == OpenModules.Count)
            //    //{
            //       module.ParentScreen.Close();
            //    //    //module.ParentScreen.Dispose();
            //    //    break;
            //    //}
            //}
        
        }

        #endregion

        //public class VietNamLocalizer : DevExpress.XtraEditors.Controls.Localizer
        //{
        //    public override string Language { get { return "VietNam"; } }

        //    public override string GetLocalizedString(DevExpress.XtraEditors.Controls.StringId id)
        //    {
        //        switch (id)
        //        {
                   
        //            case StringId.CaptionError:
        //                return "Lỗi";
        //            case StringId.InvalidValueText:
        //                return "Giá trị không hợp lệ";
        //            case StringId.CheckChecked:
        //                return "Chọn";
        //            case StringId.CheckUnchecked:
        //                return "Bỏ chọn";
        //            case StringId.CheckIndeterminate:
        //                return "Không xác định";
        //            case StringId.DateEditToday:
        //                return "Hôm nay";
        //            case StringId.DateEditClear:
        //                return "Xóa";
        //            case StringId.OK:
        //                return "Đồng  ý";
        //            case StringId.Cancel:
        //                return "Bỏ qua";
        //            case StringId.NavigatorFirstButtonHint:
        //                return "Về đầu";
        //            case StringId.NavigatorPreviousButtonHint:
        //                return "Phía trước";
        //            case StringId.NavigatorPreviousPageButtonHint:
        //                return "Phía trước";
        //            case StringId.NavigatorNextButtonHint:
        //                return "Tiếp theo";
        //            case StringId.NavigatorNextPageButtonHint:
        //                return "Tiếp theo";
        //            case StringId.NavigatorLastButtonHint:
        //                return "Cuối";
        //            case StringId.NavigatorAppendButtonHint:
        //                return "Chèn vào cuối";
        //            case StringId.NavigatorRemoveButtonHint:
        //                return "Xóa";
        //            case StringId.NavigatorEditButtonHint:
        //                return "Sửa";
        //            case StringId.NavigatorEndEditButtonHint:
        //                return "Hoàn tất";
        //            case StringId.NavigatorCancelEditButtonHint:
        //                return "Hoàn tất";
        //            case StringId.NavigatorTextStringFormat:
        //                return "Dòng thứ {0} trong số {1} dòng";
        //            case StringId.PictureEditMenuCut:
        //                return "Cắt";
        //            case StringId.PictureEditMenuCopy:
        //                return "Copy";
        //            case StringId.PictureEditMenuPaste:
        //                return "Dán";
        //            case StringId.PictureEditMenuDelete:
        //                return "Xóa";
        //            case StringId.PictureEditMenuLoad:
        //                return "Nạp";
        //            case StringId.PictureEditMenuSave:
        //                return "Lưu";
        //            case StringId.PictureEditOpenFileTitle:
        //                return "Mở file";
        //            case StringId.PictureEditSaveFileTitle:
        //                return "Lưu dạng khác";
        //            case StringId.PictureEditOpenFileError:
        //                return "Sai định dạng hình ảnh";
        //            case StringId.PictureEditOpenFileErrorCaption:
        //                return "Có lỗi";
        //            //                     case StringId.piPictureEditCopyImageError:
        //            //                         return "Không thể copy hình ảnh";
        //            case StringId.LookUpEditValueIsNull:
        //                return "[giá trị không được trống]";
        //            case StringId.LookUpInvalidEditValueType:
        //                return "Sai kiểu dữ liệu";
        //            case StringId.LookUpColumnDefaultName:
        //                return "Tên";
        //            case StringId.MaskBoxValidateError:
        //                return "Giá trị nhập liệu không hợp lệ. Bạn có muốn sửa nó không ?";
        //            case StringId.UnknownPictureFormat:
        //                return "Không hiểu định dạng hình ảnh";
        //            case StringId.DataEmpty:
        //                return "Không tồn tại giá trị hình ảnh";
        //            case StringId.NotValidArrayLength:
        //                return "Danh sách có chiều dài không hợp lệ";
        //            case StringId.ImagePopupEmpty:
        //                return "(Trống)";
        //            case StringId.ImagePopupPicture:
        //                return "(Hình ảnh)";
        //            case StringId.ColorTabCustom:
        //                return "Tùy chỉnh";
        //            case StringId.ColorTabSystem:
        //                return "Hệ thống";
        //            case StringId.TabHeaderButtonClose:
        //                return "Thoát";
        //            case StringId.XtraMessageBoxOkButtonText:
        //                return "Đồng ý";
        //            case StringId.XtraMessageBoxCancelButtonText:
        //                return "Bỏ qua";
        //            case StringId.XtraMessageBoxYesButtonText:
        //                return "Có";
        //            case StringId.XtraMessageBoxNoButtonText:
        //                return "Không";
        //            case StringId.XtraMessageBoxAbortButtonText:
        //                return "Kết thúc";
        //            case StringId.XtraMessageBoxRetryButtonText:
        //                return "Thử lại";
        //            case StringId.XtraMessageBoxIgnoreButtonText:
        //                return "Ignore";
        //            case StringId.TextEditMenuUndo:
        //                return "Undo";
        //            case StringId.TextEditMenuCut:
        //                return "Cắt";
        //            case StringId.TextEditMenuCopy:
        //                return "Copy";
        //            case StringId.TextEditMenuPaste:
        //                return "Dán";
        //            case StringId.TextEditMenuDelete:
        //                return "Xóa";
        //            case StringId.TextEditMenuSelectAll:
        //                return "Chọn tất cả";
        //            case StringId.FilterGroupAnd:
        //                return "(và)";
        //            case StringId.FilterGroupNotAnd:
        //                return "(và không:)";
        //            case StringId.FilterGroupNotOr:
        //                return "(hoặc không:)";
        //            case StringId.FilterGroupOr:
        //                return "(hoặc)";
        //            case StringId.FilterClauseAnyOf:
        //                return "(là một phần trong)";
        //            case StringId.FilterClauseBeginsWith:
        //                return "(bắt đầu với)";
        //            case StringId.FilterClauseBetween:
        //                return "(nằm giữa)";
        //            case StringId.FilterClauseBetweenAnd:
        //                return "và";
        //            case StringId.FilterClauseContains:
        //                return "(chứa)";
        //            case StringId.FilterClauseEndsWith:
        //                return "(kết thúc bằng)";
        //            case StringId.FilterClauseGreater:
        //                return "(lớn hơn)";
        //            case StringId.FilterClauseGreaterOrEqual:
        //                return "(lớn hơn hoặc bằng)";
        //            case StringId.FilterClauseIsNotNull:
        //                return "khác rỗng";
        //            case StringId.FilterClauseIsNull:
        //                return "rỗng";
                    
        //        }

        //        return base.GetLocalizedString(id);
        //    }
        //}
        //public class VietNamGridLocalizer : DevExpress.XtraGrid.Localization.GridLocalizer
        //{
        //    public override string Language { get { return "VietNam"; } }

        //    public override string GetLocalizedString(GridStringId id)
        //    {
        //        switch (id)
        //        {
        //            // ...
        //            case GridStringId.FilterPanelCustomizeButton:
        //                return "Bộ lọc";
        //            case GridStringId.CustomizationCaption:
        //                return "Tùy biến";
        //            case GridStringId.PopupFilterAll:
        //                return "(Tất cả)";
        //            case GridStringId.PopupFilterCustom:
        //                return "Tùy chọn";
        //            case GridStringId.PopupFilterBlanks:
        //                return "(Rỗng)";
        //            case GridStringId.PopupFilterNonBlanks:
        //                return "(Không rỗng)";
        //            case GridStringId.CustomFilterDialogCaption:
        //                return "Hiển thị dòng tại:";
        //            case GridStringId.CustomFilterDialogConditionEQU:
        //                return "=";
        //            case GridStringId.CustomFilterDialogConditionGT:
        //                return ">";
        //            case GridStringId.CustomFilterDialogConditionGTE:
        //                return ">=";
        //            case GridStringId.CustomFilterDialogConditionLike:
        //                return "bắt đầu với";
        //            case GridStringId.CustomFilterDialogConditionLT:
        //                return "<";
        //            case GridStringId.CustomFilterDialogConditionLTE:
        //                return "<=";
        //            case GridStringId.CustomFilterDialogConditionNEQ:
        //                return " khác ";
        //            case GridStringId.CustomFilterDialogConditionNonBlanks:
        //                return " không trống";
        //            case GridStringId.CustomFilterDialogConditionNotLike:
        //                return " không bắt đầu với";
        //            case GridStringId.CustomFilterDialogFormCaption:
        //                return "Lọc theo tiêu chí";
        //            case GridStringId.CustomFilterDialogRadioAnd:
        //                return "và";
        //            case GridStringId.CustomFilterDialogRadioOr:
        //                return "hoặc";
        //            case GridStringId.CustomFilterDialogOkButton:
        //                return "Chấp thuận";
        //            case GridStringId.CustomFilterDialogCancelButton:
        //                return "Hủy bỏ";
        //            case GridStringId.CustomFilterDialog2FieldCheck:
        //                return "Trường";
        //            case GridStringId.MenuFooterSum:
        //                return "Tổng";
        //            case GridStringId.MenuFooterMin:
        //                return "Nhỏ nhất";
        //            case GridStringId.MenuFooterMax:
        //                return "Lớn nhất";
        //            case GridStringId.MenuFooterCount:
        //                return "Đếm";
        //            case GridStringId.MenuFooterAverage:
        //                return "Trung bình";
        //            case GridStringId.MenuFooterNone:
        //                return "Không";
        //            case GridStringId.MenuFooterSumFormat:
        //                return "TỔNG={0:#.##}";
        //            case GridStringId.MenuFooterMinFormat:
        //                return "NHỎ NHẤT={0}";
        //            case GridStringId.MenuFooterMaxFormat:
        //                return "LỚN NHẤT={0}";
        //            case GridStringId.MenuFooterCountFormat:
        //                return "{0}";
        //            case GridStringId.MenuFooterAverageFormat:
        //                return "TRUNG BÌNH={0:#.##}";
        //            case GridStringId.MenuColumnSortAscending:
        //                return "Sắp xếp tăng";
        //            case GridStringId.MenuColumnSortDescending:
        //                return "Sắp xếp giảm";
        //            case GridStringId.MenuColumnGroup:
        //                return "Nhóm theo trường này";
        //            case GridStringId.MenuColumnUnGroup:
        //                return "Bỏ nhóm";
        //            case GridStringId.MenuColumnColumnCustomization:
        //                return "Tùy biến cột khi chạy";
        //            case GridStringId.MenuColumnBestFit:
        //                return "Vừa xem nhất";
        //            case GridStringId.MenuColumnFilter:
        //                return "Có thể lọc";
        //            case GridStringId.MenuColumnClearFilter:
        //                return "Bỏ lọc";
        //            case GridStringId.MenuColumnBestFitAllColumns:
        //                return "Vừa xem nhất (tất cả cột)";
        //            case GridStringId.MenuGroupPanelFullExpand:
        //                return "Mở rộng tất";
        //            case GridStringId.MenuGroupPanelFullCollapse:
        //                return "Thu hẹp tất";
        //            case GridStringId.MenuGroupPanelClearGrouping:
        //                return "Xóa nhóm";

        //            case GridStringId.FilterBuilderApplyButton:
        //                return "Áp dụng";
        //            case GridStringId.FilterBuilderCancelButton:
        //                return "Thoát";
        //            case GridStringId.FilterBuilderCaption:
        //                return "Lọc dữ liệu theo tiêu chí";
        //            case GridStringId.FilterBuilderOkButton:
        //                return "Đồng ý";
        //            case GridStringId.GridGroupPanelText:
        //                return "Kéo cột dữ liệu vào đây để tạo bộ lọc";

        //            // ...
        //        }

        //        return base.GetLocalizedString(id);
        //    }
        //}

    }

}
